package com.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.AccountDao;
import com.dao.TopicDao;
import com.mode.BBSAccount;
import com.mode.BBSTopic;

/**
 * Servlet implementation class ContentServlet
 */
@WebServlet("/ContentServlet")
public class ContentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ContentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("id");
		int topicId=Integer.parseInt(id);
//		request.setAttribute(arg0, arg1);
//		System.out.println(id);
		request.setCharacterEncoding("UTF-8");
		response.setContentType("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		BBSTopic bt=new BBSTopic();
		TopicDao td=new TopicDao();
		List<BBSTopic> list=td.find(bt);
		
		BBSAccount ba=new BBSAccount();
		AccountDao ad=new AccountDao();
		List<BBSAccount> lisa=ad.find(ba);
		
		Writer out=response.getWriter();
//		String sr="[";
		for (BBSTopic b : list) {
			String file=b.getFile();
//			System.out.println(file);
			if(b.getTopicId()==topicId){
				for (BBSAccount bb : lisa) {
					if(b.getFk_a()==bb.getAccountId()){
						String name=bb.getNickName();
						request.setAttribute("name", name);
						break;
					}
				}
				request.setAttribute("id", b.getTopicId());
				request.setAttribute("title", b.getTitle());
				request.setAttribute("topicDate", b.getTopicDate());
				request.setAttribute("content", b.getTopicTxt());
				break;
//				System.out.println(b.getTopicDate());
//				sr+="{\"id\":"+b.getTopicId()+","+"\"nickName\":"+name+"\"title\":\""+b.getTitle()+"\","+"\"topicDate\":"+b.getTopicDate()+"},";
			}
		}
//		String srr=sr.substring(0, sr.length()-1);
//		srr+="]";
//		System.out.println(srr);
//		request.setAttribute("JSON", srr);
		request.getRequestDispatcher("viewPosts.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
